package gortepfeil;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.regex.PatternSyntaxException;

/**
 * This class reads a file which contains point pairs
 * and creates a polyline of it.
 * @author Nikolai Gorte, Matthias Pfeil
 *
 */
public class PolylineImport
{
	/**
	 * Reads a file and converts the point data to a polyline.
	 * @return polyline of the points
	 * @throws IOException
	 */
	public static Polyline importPolyline() throws IOException
	{
		System.out.println("Please type in the filepath for polyline file:");
		Scanner scanner = new Scanner(System.in);
		String filepath = scanner.nextLine();
		
		File file = new File(filepath);
		if (!file.exists()) 
		{
			throw new FileNotFoundException("The file was not found at this path!");
		}
		
		
		Polyline polyline = new Polyline();
		
		try 
		{
			FileInputStream fstream = new FileInputStream(filepath);
			// Get the object of DataInputStream
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String strLine;
			
			while ((strLine = br.readLine()) != null)   
			{
				if (strLine.startsWith("#")) 
				{
					continue;
				} 
				
				double x1 = 0.0;
				double y1 = 0.0;
				double x2 = 0.0;
				double y2 = 0.0;
				
				String[] linecomps;
				try
				{
					linecomps = strLine.split(" ");

					y1 = Double.parseDouble(linecomps[0]);
					x1 = Double.parseDouble(linecomps[1]);
					y2 = Double.parseDouble(linecomps[2]);
					x2 = Double.parseDouble(linecomps[3]);
				}
				catch (PatternSyntaxException patternException)
				{
					System.out.println("Error occurred while parsing line: " + strLine);
				}

				Point pointA = new Point(x1, y1);
				Point pointB = new Point(x2, y2);
				Line newLine = new Line(pointA, pointB);
				
				polyline.addLine(newLine);
				
			}
			in.close();
			
		}
		catch (Exception e) 
		{
			System.out.println("Error occurred while reading file from: "+filepath);
		}
		
		return polyline;
	}
}

